#include "mystdio.h"
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
MYFILE* my_fopen(char* filename,char* mood)
{
    int fd=-1;
    if(strcmp(mood,"w")==0)
    {
        fd=open(filename,O_CREAT|O_WRONLY|O_TRUNC,UMASK);
    }
    else if(strcmp(mood,"r")==0)
    {
        fd=open(filename,O_RDONLY);
    }   
    else if(strcmp(mood,"a")==0)
    {
        fd=open(filename,O_CREAT|O_WRONLY|O_APPEND,UMASK);
    } 
    else if(strcmp(mood,"a+")==0)
    {
        fd=open(filename,O_CREAT|O_RDONLY|O_APPEND,UMASK);
    } 
    else {}
    
    if(fd<-1){return NULL;}
    MYFILE* fp=(MYFILE*)malloc(sizeof(MYFILE));
    
    if(!fp)
    return NULL;

    fp->fileno=fd;
    fp->flag=FLUSH_LINE;
    fp->outbuff[0]=0;
    fp->curr=0;
    fp->cap=SIZE;

    return fp;
}
void my_fflush_core(MYFILE* fp,int force)
{
    if(1==force)
    {
        write(fp->fileno,fp->outbuff,fp->curr);
    }
    else if(2==force)
    {
        if((fp->flag & FLUSH_LINE) && fp->outbuff[fp->curr-1]=='\n')
        {
            write(fp->fileno,fp->outbuff,fp->curr);
        }      
        else if((fp->flag & FLUSH_FULL) && fp->curr==fp->cap)
        {
            write(fp->fileno,fp->outbuff,fp->curr);
        } 
        else {}
    }  
}


int my_fwrite(const char* s,int size,MYFILE* fp)
{
    memcpy(fp->outbuff+fp->curr,s,size);
    fp->curr+=size;
    my_fflush_core(fp,NOMRAL);
    return size;
}

void my_fflush(MYFILE* fp)
{
    my_fflush_core(fp,FORCE);
}
void my_fclose(MYFILE* fp)
{
    if(fp->fileno>=0){
        my_fflush(fp);
        fsync(fp->fileno);
        close(fp->fileno);
        free(fp);
    }
}